package com.zyf.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.zyf.enums.PaymentTypeEnum;
import com.zyf.enums.RefundStatusEnum;
import com.zyf.model.order.OrderInfo;
import com.zyf.model.order.PaymentInfo;
import com.zyf.model.order.RefundInfo;
import com.zyf.service.OrderInfoService;
import com.zyf.service.PaymentInfoService;
import com.zyf.service.RefundInfoService;
import com.zyf.service.WXPayService;
import com.zyf.utils.HttpClient;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/** 微信支付业务层实现类
 * @author zyf
 * @date 2021年06月02日 17:38
 */
@Service
public class WXPayServiceImpl implements WXPayService {

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundInfoService refundInfoService;


    /**
     * 生成微信支付二维码
     * @author zyf
     * @date 2021/6/2 17:42
     * @param orderId 订单id
     * @return java.util.Map
     */
    @Override
    public Map createNative(String orderId) {

        try {
            //从redis中获取数据
            Map payMap = (Map)redisTemplate.opsForValue().get(orderId);
            if (payMap != null){
                return payMap;
            }

            //根据订单id获取订单信息
            OrderInfo order = orderInfoService.getById(orderId);

            //向支付记录表里添加信息
            paymentInfoService.savePaymentInfo(order, PaymentTypeEnum.WEIXIN.getStatus());
            //设置map参数
            //设置参数，生成微信支付二维码    把参数转换成Xml格式，使用商户的key进行加密
            Map paramMap = new HashMap<>();
            paramMap.put("appid", "wx74862e0dfcf69954");
            paramMap.put("mch_id", "1558950191");
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            String body = new DateTime(order.getReserveDate()).toString("yyyy-MM-dd") + "就诊"+ order.getDepname();
            paramMap.put("body", body);
            paramMap.put("out_trade_no", order.getOutTradeNo());
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");
            paramMap.put("spbill_create_ip", "127.0.0.1");
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            paramMap.put("trade_type", "NATIVE");

            //调用微信接口生成微信支付二维码
            /*reqXStream.processAnnotations(queryOrderReqDTO.getClass());
            String queryOrderXml = reqXStream.toXML(queryOrderReqDTO);*/
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //返回相关数据
            String xml = client.getContent();
            System.out.println(xml);
            //转换从Map集合
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println(resultMap);
            //封装返回集
            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", order.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));
            if (null !=resultMap.get("result_code")){
                redisTemplate.opsForValue().set(orderId,map,120, TimeUnit.MINUTES);
            }
            return map;

        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    /**
     * 调用微信接口实现支付状态查询
     * @author zyf
     * @date 2021/6/3 11:33
     * @param orderId 订单id
     * @return java.util.Map<java.lang.String,java.lang.String>
     */
    @Override
    public Map<String, String> queryPayStatus(String orderId) {
        try {
            //1、根据orderID查询订单信息
            OrderInfo orderInfo = orderInfoService.getById(orderId);

            //2、封装提交参数
            Map paramMap = new HashMap<>();
            paramMap.put("appid", "wx74862e0dfcf69954");
            paramMap.put("mch_id", "1558950191");
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

            //3、设置请求内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            //4、得到微信接口返回数据
            String content = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            System.out.println("支付状态resultMap："+resultMap);
            //5、把接口数据返回
            return resultMap;
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 调用微信接口实现微信退款
     * @author zyf
     * @date 2021/6/4 9:47
     * @param orderId 订单id
     * @return java.lang.Boolean
     */
    @Override
    public Boolean refund(String orderId) {


        try {
            //获取支付记录信息
            PaymentInfo paymentInfo = paymentInfoService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            //添加信息到退款的记录表里
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
            //判断当前订单是否已经退款
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()){
                return true;
            }
            //调用微信接口进行退款
            Map<String,String> paramMap = new HashMap<>();
            paramMap.put("appid", "wx74862e0dfcf69954");       //公众账号ID
            paramMap.put("mch_id","1558950191");   //商户编号
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
            //paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            //paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee","1");
            paramMap.put("refund_fee","1");
            String xml = WXPayUtil.generateSignedXml(paramMap, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb");

            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(xml);
            client.setHttps(true);
            //设置证书
            client.setCert(true);
            client.setCertPassword("1558950191");
            client.post();

            String content = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            if (null !=resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))){
                refundInfo.setTradeNo(resultMap.get("refund_id"))
                        .setRefundStatus(RefundStatusEnum.REFUND.getStatus())
                        .setCallbackTime(new Date())
                        .setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
